using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace GameOverlayWPF.Services
{
    /// <summary>
    /// 卡片动画扩展 - 专门为方案卡片和广告卡片提供企业级动画效果
    /// </summary>
    public static class CardAnimationExtensions
    {
        #region 卡片悬停动画

        /// <summary>
        /// 为卡片添加企业级悬停效果
        /// </summary>
        /// <param name="card">卡片元素</param>
        /// <param name="elevationEffect">是否启用海拔效果</param>
        public static void AddEnterpriseHoverEffect(this FrameworkElement card, bool elevationEffect = true)
        {
            if (card == null) return;

            // 只在需要时添加RenderTransform，不改变卡片的原始状态
            if (card.RenderTransform == null || card.RenderTransform == Transform.Identity)
            {
                var transformGroup = new TransformGroup();
                transformGroup.Children.Add(new ScaleTransform(1.0, 1.0));
                transformGroup.Children.Add(new TranslateTransform(0, 0));
                card.RenderTransform = transformGroup;
                card.RenderTransformOrigin = new Point(0.5, 0.5);
            }
            // 如果已有TranslateTransform，升级为TransformGroup以支持缩放
            else if (card.RenderTransform is TranslateTransform existingTranslate)
            {
                var transformGroup = new TransformGroup();
                transformGroup.Children.Add(new ScaleTransform(1.0, 1.0));
                transformGroup.Children.Add(existingTranslate);
                card.RenderTransform = transformGroup;
                card.RenderTransformOrigin = new Point(0.5, 0.5);
            }

            // 添加阴影效果（如果需要）
            if (elevationEffect && card.Effect == null)
            {
                card.Effect = new System.Windows.Media.Effects.DropShadowEffect
                {
                    Color = Colors.Black,
                    BlurRadius = 8,
                    ShadowDepth = 2,
                    Opacity = 0.0,
                    Direction = 270
                };
            }

            card.MouseEnter += (s, e) => AnimateCardHover(card, true, elevationEffect);
            card.MouseLeave += (s, e) => AnimateCardHover(card, false, elevationEffect);
        }

        private static void AnimateCardHover(FrameworkElement card, bool isEntering, bool elevationEffect)
        {
            var transformGroup = card.RenderTransform as TransformGroup;
            if (transformGroup == null || transformGroup.Children.Count < 2) return;
            
            var scaleTransform = transformGroup.Children[0] as ScaleTransform;
            var translateTransform = transformGroup.Children[1] as TranslateTransform;
            if (scaleTransform == null || translateTransform == null) return;

            var storyboard = new Storyboard();
            var duration = TimeSpan.FromMilliseconds(200);
            var easing = new QuadraticEase { EasingMode = EasingMode.EaseOut };

            // 缩放动画
            var targetScale = isEntering ? 1.03 : 1.0;
            var scaleXAnim = new DoubleAnimation(scaleTransform.ScaleX, targetScale, duration) { EasingFunction = easing };
            var scaleYAnim = new DoubleAnimation(scaleTransform.ScaleY, targetScale, duration) { EasingFunction = easing };

            Storyboard.SetTarget(scaleXAnim, scaleTransform);
            Storyboard.SetTargetProperty(scaleXAnim, new PropertyPath(ScaleTransform.ScaleXProperty));
            Storyboard.SetTarget(scaleYAnim, scaleTransform);
            Storyboard.SetTargetProperty(scaleYAnim, new PropertyPath(ScaleTransform.ScaleYProperty));

            storyboard.Children.Add(scaleXAnim);
            storyboard.Children.Add(scaleYAnim);

            // 垂直位移动画（轻微上升效果）
            var targetY = isEntering ? -3 : 0;
            var translateYAnim = new DoubleAnimation(translateTransform.Y, targetY, duration) { EasingFunction = easing };
            
            Storyboard.SetTarget(translateYAnim, translateTransform);
            Storyboard.SetTargetProperty(translateYAnim, new PropertyPath(TranslateTransform.YProperty));
            storyboard.Children.Add(translateYAnim);

            // 阴影动画
            if (elevationEffect && card.Effect is System.Windows.Media.Effects.DropShadowEffect shadow)
            {
                var targetOpacity = isEntering ? 0.25 : 0.0;
                var targetBlur = isEntering ? 15 : 8;
                var targetDepth = isEntering ? 4 : 2;

                var shadowOpacityAnim = new DoubleAnimation(shadow.Opacity, targetOpacity, duration) { EasingFunction = easing };
                var shadowBlurAnim = new DoubleAnimation(shadow.BlurRadius, targetBlur, duration) { EasingFunction = easing };
                var shadowDepthAnim = new DoubleAnimation(shadow.ShadowDepth, targetDepth, duration) { EasingFunction = easing };

                Storyboard.SetTarget(shadowOpacityAnim, shadow);
                Storyboard.SetTargetProperty(shadowOpacityAnim, new PropertyPath(System.Windows.Media.Effects.DropShadowEffect.OpacityProperty));
                
                Storyboard.SetTarget(shadowBlurAnim, shadow);
                Storyboard.SetTargetProperty(shadowBlurAnim, new PropertyPath(System.Windows.Media.Effects.DropShadowEffect.BlurRadiusProperty));
                
                Storyboard.SetTarget(shadowDepthAnim, shadow);
                Storyboard.SetTargetProperty(shadowDepthAnim, new PropertyPath(System.Windows.Media.Effects.DropShadowEffect.ShadowDepthProperty));

                storyboard.Children.Add(shadowOpacityAnim);
                storyboard.Children.Add(shadowBlurAnim);
                storyboard.Children.Add(shadowDepthAnim);
            }

            storyboard.Begin();
        }

        #endregion

        #region 卡片点击动画

        /// <summary>
        /// 卡片点击反馈动画 - 企业级Material Design风格
        /// </summary>
        /// <param name="card">卡片元素</param>
        /// <returns>动画任务</returns>
        public static async Task AnimateCardClickAsync(this FrameworkElement card)
        {
            var transformGroup = card?.RenderTransform as TransformGroup;
            var scaleTransform = transformGroup?.Children[0] as ScaleTransform;
            if (scaleTransform != null)
            {
                var storyboard = new Storyboard();
                var easing = new BackEase { EasingMode = EasingMode.EaseOut, Amplitude = 0.3 };

                // 按下效果
                var scaleDownX = new DoubleAnimation(1.0, 0.96, TimeSpan.FromMilliseconds(100)) { EasingFunction = easing };
                var scaleDownY = new DoubleAnimation(1.0, 0.96, TimeSpan.FromMilliseconds(100)) { EasingFunction = easing };

                // 释放效果
                var scaleUpX = new DoubleAnimation(0.96, 1.0, TimeSpan.FromMilliseconds(200)) 
                { 
                    EasingFunction = easing,
                    BeginTime = TimeSpan.FromMilliseconds(100)
                };
                var scaleUpY = new DoubleAnimation(0.96, 1.0, TimeSpan.FromMilliseconds(200)) 
                { 
                    EasingFunction = easing,
                    BeginTime = TimeSpan.FromMilliseconds(100)
                };

                Storyboard.SetTarget(scaleDownX, scaleTransform);
                Storyboard.SetTargetProperty(scaleDownX, new PropertyPath(ScaleTransform.ScaleXProperty));
                Storyboard.SetTarget(scaleDownY, scaleTransform);
                Storyboard.SetTargetProperty(scaleDownY, new PropertyPath(ScaleTransform.ScaleYProperty));

                Storyboard.SetTarget(scaleUpX, scaleTransform);
                Storyboard.SetTargetProperty(scaleUpX, new PropertyPath(ScaleTransform.ScaleXProperty));
                Storyboard.SetTarget(scaleUpY, scaleTransform);
                Storyboard.SetTargetProperty(scaleUpY, new PropertyPath(ScaleTransform.ScaleYProperty));

                storyboard.Children.Add(scaleDownX);
                storyboard.Children.Add(scaleDownY);
                storyboard.Children.Add(scaleUpX);
                storyboard.Children.Add(scaleUpY);

                var tcs = new TaskCompletionSource<bool>();
                storyboard.Completed += (s, e) => tcs.SetResult(true);

                storyboard.Begin();
                await tcs.Task;
            }
        }

        #endregion

        #region 卡片加载状态

        /// <summary>
        /// 卡片骨架屏动画 - 优雅的加载占位效果
        /// </summary>
        /// <param name="card">卡片元素</param>
        /// <param name="isLoading">是否处于加载状态</param>
        public static void SetCardLoadingState(this FrameworkElement card, bool isLoading)
        {
            if (card == null) return;

            card.Dispatcher.Invoke(() =>
            {
                if (isLoading)
                {
                    StartSkeletonAnimation(card);
                }
                else
                {
                    StopSkeletonAnimation(card);
                }
            });
        }

        private static void StartSkeletonAnimation(FrameworkElement card)
        {
            // 创建骨架屏渐变背景
            var skeletonBrush = new LinearGradientBrush
            {
                StartPoint = new Point(0, 0),
                EndPoint = new Point(1, 0),
                GradientStops = new GradientStopCollection
                {
                    new GradientStop(Color.FromArgb(40, 255, 255, 255), 0.0),
                    new GradientStop(Color.FromArgb(80, 255, 255, 255), 0.5),
                    new GradientStop(Color.FromArgb(40, 255, 255, 255), 1.0)
                }
            };

            // 创建覆盖层
            var overlay = new Border
            {
                Background = skeletonBrush,
                Opacity = 0.0
            };

            // 添加到卡片
            if (card is Panel panel)
            {
                panel.Children.Add(overlay);
                card.Tag = overlay;
            }
            else if (card is ContentControl contentControl)
            {
                var grid = new Grid();
                grid.Children.Add(contentControl.Content as UIElement);
                grid.Children.Add(overlay);
                contentControl.Content = grid;
                card.Tag = overlay;
            }

            // 创建波浪动画
            var storyboard = new Storyboard { RepeatBehavior = RepeatBehavior.Forever };

            var opacityAnimation = new DoubleAnimation(0.0, 1.0, TimeSpan.FromMilliseconds(1500))
            {
                EasingFunction = new SineEase { EasingMode = EasingMode.EaseInOut },
                AutoReverse = true
            };

            var transformAnimation = new DoubleAnimation(-100, 100, TimeSpan.FromMilliseconds(2000))
            {
                EasingFunction = new SineEase { EasingMode = EasingMode.EaseInOut }
            };

            // 应用变换
            var transform = new TranslateTransform();
            skeletonBrush.Transform = transform;

            Storyboard.SetTarget(opacityAnimation, overlay);
            Storyboard.SetTargetProperty(opacityAnimation, new PropertyPath(UIElement.OpacityProperty));

            Storyboard.SetTarget(transformAnimation, transform);
            Storyboard.SetTargetProperty(transformAnimation, new PropertyPath(TranslateTransform.XProperty));

            storyboard.Children.Add(opacityAnimation);
            storyboard.Children.Add(transformAnimation);

            overlay.Tag = storyboard;
            storyboard.Begin();
        }

        private static void StopSkeletonAnimation(FrameworkElement card)
        {
            if (card.Tag is Border overlay && overlay.Tag is Storyboard storyboard)
            {
                storyboard.Stop();
                
                // 移除覆盖层
                if (card is Panel panel)
                {
                    panel.Children.Remove(overlay);
                }
                
                card.Tag = null;
            }
        }

        #endregion

        #region 卡片刷新动画

        /// <summary>
        /// 卡片数据刷新动画 - 优雅的内容更新效果
        /// </summary>
        /// <param name="card">卡片元素</param>
        /// <returns>动画任务</returns>
        public static async Task AnimateCardRefreshAsync(this FrameworkElement card)
        {
            if (card == null) return;

            await card.Dispatcher.InvokeAsync(async () =>
            {
                var storyboard = new Storyboard();
                var easing = new QuadraticEase { EasingMode = EasingMode.EaseInOut };

                // 创建旋转变换
                RotateTransform rotateTransform;
                if (card.RenderTransform is TransformGroup transformGroup && transformGroup.Children.Count > 2)
                {
                    rotateTransform = transformGroup.Children[2] as RotateTransform;
                    if (rotateTransform == null)
                    {
                        rotateTransform = new RotateTransform();
                        transformGroup.Children.Add(rotateTransform);
                    }
                }
                else
                {
                    var newGroup = new TransformGroup();
                    newGroup.Children.Add(new ScaleTransform(1.0, 1.0));
                    newGroup.Children.Add(new TranslateTransform(0, 0));
                    rotateTransform = new RotateTransform();
                    newGroup.Children.Add(rotateTransform);
                    card.RenderTransform = newGroup;
                    card.RenderTransformOrigin = new Point(0.5, 0.5);
                }

                // 淡出 + 轻微旋转
                var fadeOutAnimation = new DoubleAnimation(1.0, 0.3, TimeSpan.FromMilliseconds(200)) { EasingFunction = easing };
                var rotateAnimation = new DoubleAnimation(0, 5, TimeSpan.FromMilliseconds(200)) { EasingFunction = easing };

                // 淡入 + 恢复旋转
                var fadeInAnimation = new DoubleAnimation(0.3, 1.0, TimeSpan.FromMilliseconds(200)) 
                { 
                    EasingFunction = easing,
                    BeginTime = TimeSpan.FromMilliseconds(250)
                };
                var rotateBackAnimation = new DoubleAnimation(5, 0, TimeSpan.FromMilliseconds(200)) 
                { 
                    EasingFunction = easing,
                    BeginTime = TimeSpan.FromMilliseconds(250)
                };

                Storyboard.SetTarget(fadeOutAnimation, card);
                Storyboard.SetTargetProperty(fadeOutAnimation, new PropertyPath(UIElement.OpacityProperty));

                Storyboard.SetTarget(rotateAnimation, rotateTransform);
                Storyboard.SetTargetProperty(rotateAnimation, new PropertyPath(RotateTransform.AngleProperty));

                Storyboard.SetTarget(fadeInAnimation, card);
                Storyboard.SetTargetProperty(fadeInAnimation, new PropertyPath(UIElement.OpacityProperty));

                Storyboard.SetTarget(rotateBackAnimation, rotateTransform);
                Storyboard.SetTargetProperty(rotateBackAnimation, new PropertyPath(RotateTransform.AngleProperty));

                storyboard.Children.Add(fadeOutAnimation);
                storyboard.Children.Add(rotateAnimation);
                storyboard.Children.Add(fadeInAnimation);
                storyboard.Children.Add(rotateBackAnimation);

                var tcs = new TaskCompletionSource<bool>();
                storyboard.Completed += (s, e) => tcs.SetResult(true);

                storyboard.Begin();
                await tcs.Task;
            });
        }

        #endregion
    }
}
